﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WinHttp;
using System.IO;
using ServerHelper;
using System.Runtime.InteropServices;
using System.Security.Cryptography; 
using System.Collections;
using System.Windows.Navigation;
using System.Xml;

namespace HomeMediaBrowser
{
    /// <summary>
    /// Interaction logic for MainPanel.xaml
    /// </summary>
    /// 

    public partial class CUITabItem : TabItem
    {
        public static readonly DependencyProperty DataProperty =
          DependencyProperty.Register("UIData",typeof(UITabItemData),typeof(CUITabItem));
              
      public UITabItemData Data
      {
          get { return (UITabItemData)GetValue(DataProperty); }
          set { SetValue(DataProperty, value); }
      }
    }
    public class MediaDataTemplateSelector : DataTemplateSelector
    {
        public override DataTemplate
            SelectTemplate(object item, DependencyObject container)
        {
            return System.Windows.Application.Current.FindResource("emptyDataTemplate") as DataTemplate;
        }
    }
    public partial class MainPanel : Page
    {
        public MainPanel()
        {
            MediaLibrary = new MediaLibaryList();
            LibraryMedias = new Hashtable();
            DownloadHelpers = new Hashtable();
            HistoryPaths = new List<UITabItemData>();
            InitializeComponent();
            ObjectDataProvider odp = FindResource("PathListResource") as ObjectDataProvider;
            PathsList = odp.Data as PathList;
            TabHome = new UITabItemData("Home Page", "#HomePage");
            TabHome.IsSelected = true;
            PathsList.Add(TabHome);
            HistoryIndex = 0;
            AddHistoryPath(TabHome);

            IsServer = false;
            
            //InitServer();
        }
        UITabItemData TabHome;
        //public virtual void UnLoaded()
        //{
        //    MainWindow MW = App.Current.MainWindow as MainWindow;
        //    MW.GetDownloadPage().SaveDownloadList();
        //}
        
        DownloadHelper RootHelper;
        public string ServerIP { get; set; }
        public int InitServer(bool bServer)
        {
            IsServer = bServer;
            if (IsServer)
            {
                GridAll.RowDefinitions[0].Height = new GridLength(0);
                GridAll.RowDefinitions[1].Height = new GridLength(0);
            }
            RootHelper = new DownloadHelper(this, TaskType.TASK_ROOT,"");

            String AppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            AppData += "\\DoCoMedia\\WinHomeServer\\ClientReceive\\";
            Directory.CreateDirectory(AppData);

            MainWindow MW = App.Current.MainWindow as MainWindow;
            DownloadPage DP = MW.GetDownloadPage();

            DP.LoadDownloadList();
            return 0;
        }
        public void DownloadPercent(string path, int percent)
        {
            MainWindow MW = App.Current.MainWindow as MainWindow;
            DownloadPage DP = MW.GetDownloadPage();
            DP.DownloadPercent(path,percent);

        }
        public void RefreshMedia(string path)
        {
            MainWindow MW = App.Current.MainWindow as MainWindow;
            DownloadPage DP = MW.GetDownloadPage();
            DP.RefreshMedia(path);

        }
        public void OpenDownloadedFile(string path)
        {
            string localpath = GetCachePath(path);
            IntPtr result = NativeMethods.ShellExecuteW((IntPtr)0, "open", "explorer", localpath, null, 1 /* SW_SHOWNORMAL */);
        }
        public bool CanGetThumbnail(ThumbType Type)
        {
            return (Type == ThumbType.THUMB_VIDEO || Type == ThumbType.THUMB_AUDIO || Type == ThumbType.THUMB_IMAGE);
        }
        public void GetThumbnailFromServer(string path)
        {
            DownloadHelper MediaHelper = new DownloadHelper(this, TaskType.TASK_MEDIATHUMB, path);
        }

        public Boolean IsServer;

        public int ResetRootData()
        {
            MediaLibrary.Clear();
            int Count = PathsList.Count;
            for (int i = 1; i < Count; i++)
            {
                PathsList.RemoveAt(1);
            }
            TabHome.IsSelected = true;

            if (IsServer)
            {
                UIListItemData Item = new UIListItemData();
                Item.InitThumb(ThumbType.THUMB_ADDSERVERFOLDER);
                MediaLibrary.Add(Item);
            }
            return 0;
        }
        public int AddRootFolder(SERVERDATA_SHAREDFOLDER ShareFolder)
        {
            UIListItemData Item = CreateItemByShareFolder(ShareFolder);
            if (IsServer)
                MediaLibrary.Insert(MediaLibrary.Count - 1, Item);
            else
                MediaLibrary.Add(Item);
            return 0;
        }
        public UIListItemData CreateItemByShareFolder(SERVERDATA_SHAREDFOLDER ShareFolder)
        {
            UIListItemData Item = new UIListItemData();
            Item.Path = ShareFolder.szPath;
            int nIndex = Item.Path.LastIndexOf('\\');
            if (nIndex >= 0)
                Item.Name = Item.Path.Substring(nIndex + 1, Item.Path.Length - nIndex - 1);
            else
                Item.Name = Item.Path;
            Item.IsServer = IsServer;
            Item.InitThumb(ThumbType.THUMB_FOLDER);
            return Item;
        }
        public void FinishRootFolder()
        {
            Binding b = new Binding();
            b.Mode = BindingMode.OneWay;
            b.Source = MediaLibrary;

            CurrentView.SetBinding(ListView.ItemsSourceProperty, b);

            WardButton();
        }
        public MediaLibaryList MediaLibrary;

        public Hashtable DownloadHelpers;
        public PathList PathsList;

        public virtual void CurrentViewDoubleClick(object sender, RoutedEventArgs e)
        {
            if (IsServer)
                OnDoubleClickServerItem(sender,e);
            else if (CurrentPath == null)
                OnDoubleClickLibrary(sender, e);
            else
                OnDoubleClickMedias(sender, e);
        }
        public virtual void OnDoubleClickServerItem(object sender, RoutedEventArgs e)
        {
            UIListItemData ItemData = CurrentView.SelectedItem as UIListItemData;
            if (ItemData == null)
                return;
            if (ItemData.Type == ThumbType.THUMB_ADDSERVERFOLDER)
            {
                System.Windows.Forms.FolderBrowserDialog Fd = new System.Windows.Forms.FolderBrowserDialog();
                System.Windows.Forms.DialogResult Dr = Fd.ShowDialog();
                string strDr = Dr.ToString();
                string path = Fd.SelectedPath;
                DownloadHelper MediaHelper = new DownloadHelper(this, TaskType.TASK_ADDSERVERFOLDER, path);
            }
        }

        public static RoutedEvent PlayURLEvent = EventManager.RegisterRoutedEvent("PlayURLEvent", RoutingStrategy.Bubble,
                                        typeof(RoutedEventHandler), typeof(MainPanel));
        public static RoutedEvent PlayEvent = EventManager.RegisterRoutedEvent("PlayEvent", RoutingStrategy.Bubble,
                                        typeof(RoutedEventHandler), typeof(MainPanel));

        public virtual void CurrentViewClick(object sender, RoutedEventArgs e)
        {
            //may be scroll bar button
            Button clickButton = e.OriginalSource as Button;
            if (clickButton == null)
                return;
            UIListItemData ItemData = clickButton.DataContext as UIListItemData;

            if (ItemData == null)
                return;

            string clickButtonName = clickButton.Name;
            if (clickButtonName == "DownloadButton")
            {
                MainWindow MW = App.Current.MainWindow as MainWindow;
                DownloadPage DP = MW.GetDownloadPage();
                DP.AddNewDownloadItem(ItemData);
                DP.SaveDownloadList();
            }
            else if (clickButtonName == "CloseButton")
            {
                DownloadHelper MediaHelper = new DownloadHelper(this, TaskType.TASK_REMOVESERVERFOLDER, ItemData.Path);
            }
            else if (clickButtonName == "PlayButton")
            {
               RoutedEventArgs args = new RoutedEventArgs(PlayURLEvent, ItemData);
               RaiseEvent(args);
             }
        }
        
        public virtual void OnDoubleClickLibrary(object sender, RoutedEventArgs e)
        {
            UIListItemData Item = CurrentView.SelectedItem as UIListItemData;
            if (Item == null)
                return;
            CurrentPath = null;
            DownloadHelper MediaHelper = new DownloadHelper(this, TaskType.TASK_MEDIAS,Item.Path);
        }
        public void PrepareFolder(string Path)
        {
            //
            int Count = PathsList.Count;
            int nIndex = -1;
            if (CurrentPath != null && CurrentPath.Contains(Path))
            {
                //remove last  
                for (int i = 0;i<Count;i++)
                {
                    UITabItemData item = PathsList[i] as UITabItemData;
                    if (item.Path.Contains(Path))
                    {
                        nIndex = i;
                        if (nIndex == 0 )
                            item.IsSelected = true;
                        break;
                    }
                }
                for (int i = 0;i< Count - nIndex && nIndex >= 1;i++)
                {
                    PathsList.RemoveAt(nIndex);
                }
            }
            Count = PathsList.Count;
            for (int i = 0; i < Count; i++)
            {
                UITabItemData item = PathsList[i] as UITabItemData;
                if (item == null)
                    continue;
                if (i == nIndex)
                    item.IsSelected = true;
                else
                    item.IsSelected = false;
            }
            //add to end
            {
                //Remove all but root Tab,the add to end
                int nSlashIndex = Path.LastIndexOf('\\');
                string name = Path.Substring(nSlashIndex + 1, Path.Length - nSlashIndex - 1);

                UITabItemData itemData = new UITabItemData(name, Path);
                itemData.IsSelected = true;
                PathsList.Add(itemData);
                AddHistoryPath(itemData);

                MediaLibaryList MediasList = new MediaLibaryList();

                Binding b = new Binding();
                b.Mode = BindingMode.OneWay;
                b.Source = MediasList;
                CurrentView.SetBinding(ListView.ItemsSourceProperty, b);

                LibraryMedias.Remove(GetMd5HashString(Path));
                LibraryMedias.Add(GetMd5HashString(Path), MediasList);
            }
            //Add New Tab at the end; 
            {
                
            }
            CurrentPath = Path;
        }
        public void FinishFolder(string Path)
        {

        }
        public int AddFolderMedia(string Path,SERVERDATA_MEDIA ShareFolder)
        {
            UIListItemData Item = new UIListItemData();
            Item.Path = ShareFolder.szPath;
            Item.Name = ShareFolder.szName;
            if (ShareFolder.isFolder != 0)
                 Item.InitThumb(ThumbType.THUMB_FOLDER);
            else
            {
                switch (ShareFolder.FileType)
                {
                    case eFileType.FileType_Video:
                        Item.InitThumb(ThumbType.THUMB_VIDEO);
                        break;
                    case eFileType.FileType_Audio:
                        Item.InitThumb(ThumbType.THUMB_AUDIO);
                        break;
                    case eFileType.FileType_Image:
                        Item.InitThumb(ThumbType.THUMB_IMAGE);
                        break;
                    case eFileType.FileType_Binary://now do not show binary 
                        return 0;
                    default:
                        Item.InitThumb(ThumbType.THUMB_OTHER);
                        break;
                }
            }
            if (CanGetThumbnail(Item.Type))
                GetThumbnailFromServer(Item.Path);

            MediaLibaryList Medias = LibraryMedias[GetMd5HashString(Path)] as MediaLibaryList;
            Medias.Add(Item);
            return 0;
        }
        string CurrentPath{get;set;}
        Hashtable LibraryMedias;

        public virtual void ServerFolderClick(object sender, RoutedEventArgs e)
        {
            FrameworkElement t = sender as FrameworkElement;
            if (t == null)
                return;
            UITabItemData Item = t.DataContext as UITabItemData;
            if (Item == null)
                return;
            string path = Item.Path;
            if (path == "#HomePage")
                RootHelper = new DownloadHelper(this, TaskType.TASK_ROOT, "");
            else
                new DownloadHelper(this, TaskType.TASK_MEDIAS, path);
        }
        public virtual void ServerFolderListClick(object sender, RoutedEventArgs e)
        {
            ServerFolderClick(sender, e); return;
            FrameworkElement t = sender as FrameworkElement;
            if (t == null)
                return;
            UITabItemData Item = t.DataContext as UITabItemData;
            if (Item == null)
                return;            
        }

        public virtual void OnDoubleClickMedias(object sender, RoutedEventArgs e)
        {
            UIListItemData Item = CurrentView.SelectedItem as UIListItemData;
            if (Item != null && Item.Type == ThumbType.THUMB_FOLDER)
            {
                DownloadHelper MediaHelper = new DownloadHelper(this, TaskType.TASK_MEDIAS, Item.Path);
            }
            else if (Item != null)
            {
                RoutedEventArgs args = new RoutedEventArgs(PlayURLEvent, Item);
                RaiseEvent(args);
            }
        }
        public static string RemoveInvalidFileNameChars(string fileName)
        {
            char[] invalidFileChars = System.IO.Path.GetInvalidFileNameChars();
            foreach (char invalidFChar in invalidFileChars)
            {
                fileName = fileName.Replace(invalidFChar.ToString(), "");
            }
            return fileName;
        }
        public string GetMd5HashPath(string Param)
        {
            return RemoveInvalidFileNameChars(GetMd5HashString(Param));
        }
        public string GetMd5HashString(string Param)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] message;
            message=Encoding.Default.GetBytes(Param);
            md5.ComputeHash(message);
            string Md5string = Convert.ToBase64String(md5.Hash);
            Md5string = RemoveInvalidFileNameChars(Md5string);

            return Md5string;
        }


        public void RefreshThumb(string path, byte[] thumbdata)
        {
            MediaLibaryList Medias = null;
            if (CurrentPath != null && CurrentPath.Length > 0)
                Medias = LibraryMedias[GetMd5HashString(CurrentPath)] as MediaLibaryList;
             int i = 0;
             int Count;
            if (Medias != null)
            {
                Count = Medias.Count;
                for (i = 0; i < Count; i++)
                {
                    UIListItemData item = Medias[i];
                    if (item != null && item.Path == path)
                    {
                        MemoryStream Ms = new MemoryStream(thumbdata);
                        ImageSourceConverter imageSourceConverter = new ImageSourceConverter();
                        item.SetThumbVisible(Visibility.Visible);
                        item.ThumbBrush.ImageSource = (ImageSource)imageSourceConverter.ConvertFrom(Ms);
                    }
                }
            }
            MainWindow MW = App.Current.MainWindow as MainWindow;
            DownloadPage DP = MW.GetDownloadPage();
            DP.RefreshThumb(path, thumbdata);

        }
        public string GetCachePath(string path)
        {
            int nIndex = path.LastIndexOf('\\');
            string postsuffix = ".cache";
            if (nIndex >= 0)
                postsuffix = path.Substring(nIndex+1);
            String AppData = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            AppData += "\\Download\\";
            Directory.CreateDirectory(AppData);

            //AppData += GetMd5HashString(path);
            //AppData += ".cache";
            AppData += postsuffix;
            return AppData;
        }
        public void ShowServerStatus(byte[] xmlBody)
        {
            string xmlText = System.Text.Encoding.UTF8.GetString(xmlBody);

            MessageBox.Show(xmlText);
        }

        public void AddHistoryPath(UITabItemData ItemData)
        {
            if (HistoryIndex > 0 && HistoryIndex <= HistoryPaths.Count && HistoryPaths[HistoryIndex - 1].Path == ItemData.Path)
            {
                WardButton();
                return;
            }        
            if (HistoryIndex != HistoryPaths.Count && HistoryIndex < HistoryPaths.Count)
            {
                //search back to history

                if (HistoryPaths[HistoryIndex].Path != ItemData.Path)
                {
                    //remove all forward history
                    while (HistoryIndex < HistoryPaths.Count)
                    {
                        HistoryPaths.RemoveAt(HistoryIndex);
                    }
                }
            }
                
            HistoryPaths.Add(ItemData);
            HistoryIndex++;

            WardButton();
        }
        public List<UITabItemData> HistoryPaths;
        public int HistoryIndex;

        public void WardButton()
        {
            if (HistoryIndex <= 1)
                BackwardButton.IsEnabled = false;
            else
                BackwardButton.IsEnabled = true;
            if (HistoryIndex >= HistoryPaths.Count)
                ForwardButton.IsEnabled = false;
            else
                ForwardButton.IsEnabled = true;
        }
        public virtual void OnForward(object sender, RoutedEventArgs e)
        {
            if (HistoryIndex >= HistoryPaths.Count)
                return;
            HistoryIndex++;
            UITabItemData Item = HistoryPaths[HistoryIndex-1];
            DownloadHelper MediaHelper = new DownloadHelper(this, TaskType.TASK_MEDIAS, Item.Path);
        }
        public virtual void OnBackward(object sender, RoutedEventArgs e)
        {
            if (HistoryIndex <= 1)
                return;
            HistoryIndex--;
            if (HistoryIndex >= HistoryPaths.Count)
                return;
            UITabItemData Item = HistoryPaths[HistoryIndex-1];
            string path = Item.Path;
            if (path == "#HomePage")
                RootHelper = new DownloadHelper(this, TaskType.TASK_ROOT, "");
            else
                new DownloadHelper(this, TaskType.TASK_MEDIAS, path);
        }       
    }
}
